package com.xindacloud.sms.adapter.service.factory;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.clxcommunications.xms.ApiConnection;
import com.xindacloud.sms.adapter.entity.SmsAgent;
import com.xindacloud.sms.adapter.entity.SmsAgentGroup;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsAgentGroupService;
import com.xindacloud.sms.adapter.service.business.ISmsAgentService;
import com.xindacloud.sms.adapter.utils.AgentEnum;
import com.xindacloud.sms.adapter.utils.Base64DecodeHelp;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
@Scope("prototype")
public class SinchClientFactory {

    private final ISmsAgentService smsAgentService;

    private final ISmsAgentGroupService smsAgentGroupService;

    @Autowired
    public SinchClientFactory(ISmsAgentService smsAgentService, ISmsAgentGroupService smsAgentGroupService) {
        this.smsAgentService = smsAgentService;
        this.smsAgentGroupService = smsAgentGroupService;
    }


    public ApiConnection getSinchClient(String apiKey, String apiSecret, String baseUri) {
        return ApiConnection.builder()
                .servicePlanId(apiKey)
                .token(apiSecret)
                .endpoint(baseUri)
                .start();
    }


    public ApiConnection getRandomSinchClient() {

        SmsAgentGroup smsAgentGroup = smsAgentGroupService.queryOneAgentInfoByName(AgentEnum.SINCH_AGENT.getAgentName());
        if (Objects.isNull(smsAgentGroup)) {
            throw new ServiceException("没有找到可用的通道组.", UnionResultHelp.StatusEnum.NotFound.code());
        }
        List<SmsAgent> agentList = smsAgentService.queryAvailableAgent(smsAgentGroup.getGroupId());
        if (CollectionUtils.isEmpty(agentList)) {
            throw new ServiceException("没有可用的服务通道.", UnionResultHelp.StatusEnum.NotFound.code());
        }
        SmsAgent sinchDefaultAgent = agentList.get(new Random().nextInt(agentList.size()));
        return getSinchClient(Base64DecodeHelp.decode(sinchDefaultAgent.getApiKey()),
                Base64DecodeHelp.decode(sinchDefaultAgent.getApiSecret()), sinchDefaultAgent.getApiUrl());

    }
}
